package org.yagnus.yadoop

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io._;

class LongArrayWritable extends WritableComparable[LongArrayWritable] {
    var array : Array[Long] = null;

    var equalLengthOnly = true;

    def this(in : Array[Long]) {
        this();
        set(in);
    }

    def set(values : Array[Long]) = {
        this.array = values;
    }

    def get : Array[Long] = array;

    override def readFields(in : DataInput) {
        array = new Array[Long](in.readInt); // construct values
        for (i ← 0 until array.length)
            array(i) = in.readLong
    }

    override def write(out : DataOutput) {
        if (array == null) {
            out.writeInt(0);
        } else {
            out.writeInt(array.length);
            for (l ← array) {
                out.writeLong(l);
            }
        }
    }

    override def equals(o : Any) : Boolean = {
        if (o == null) return false;
        if (!o.isInstanceOf[LongArrayWritable]) return false;
        return compareTo(o.asInstanceOf[LongArrayWritable]) == 0;
    }
    override def compareTo(o : LongArrayWritable) : Int = {
        if (o eq null) {
            if (equalLengthOnly) throw new LongArrayWritableError("LongArrayWritable.compaerTo received a null array to compare to.");
            return 1;
        }
        if (array.length == o.array.length) {
            for (i ← 0 until array.length) {
                if (this.array(i) > o.array(i)) {
                    return 1
                } else if (this.array(i) < o.array(i)) {
                    return -1;
                }
            }
            return 0;
        } else if (array.length > o.array.length) {
            if (equalLengthOnly) throw new LongArrayWritableError("LongArrayWritable.compaerTo received a comparison to a shorter array");
            return 1;
        } else {
            if (equalLengthOnly) throw new LongArrayWritableError("LongArrayWritable.compaerTo received a comparison to a longer array");
            return -1;
        }
    }
}

class LongArrayWritableError(x : String) extends Exception(x) {
}
